#include "CSysFile.h"


CSysFile::CSysFile():m_fd(-1)
{}

CSysFile::~CSysFile()
{
	Close();
}

bool CSysFile::Open(const char* filename,int oflag)
{
	assert(filename!=NULL);
	Close();
	m_fd = open(filename,oflag);
	return (m_fd!=-1);
}

int CSysFile::Read(void *buffer,unsigned int count)
{
	assert(m_fd!=-1);
	return read(m_fd,buffer,count);
}

int CSysFile::Write(const void *buffer,unsigned int count)
{
	assert(m_fd!=-1);
	return write(m_fd,buffer,count);
}
void CSysFile::Close()
{
	if (m_fd!=-1)
	{
		close(m_fd);
		m_fd = -1;
	}
}

long CSysFile::Seek(long offset,int origin)
{
	assert(m_fd!=-1);
	return lseek(m_fd,offset,origin);
}

long CSysFile::Tell()
{
	assert(m_fd!=-1);
	return lseek(m_fd,0,SEEK_CUR);
}
bool CSysFile::Sync()
{
	assert(m_fd!=-1);
#ifdef WIN32
	return (::_commit(m_fd)==0);
#else
	return (fsync(m_fd)==0);
#endif
}

//bool CSysFile::Eof()
//{
//	assert(m_fd!=-1);
//#ifdef WIN32
//	return ::_eof(m_fd);
//#else
//	long current = lseek(m_fd,0,SEEK_CUR);
//	bool ret = (current==lseek(m_fd,0,SEEK_END));
//	lseek(m_fd,current,SEEK_SET);
//	return ret;
//#endif
//}

long CSysFile::GetLength()
{
	assert(m_fd!=-1);
	long lcurrent = Seek(0,SEEK_END);
	return Seek(lcurrent,SEEK_SET);
}
long CSysFile::GetLength(const char* filename)
{
	struct stat f_stat;
	if (stat(filename, &f_stat) == -1) {
		return -1;
	}
	return (long)f_stat.st_size;
}

bool CSysFile::Setlength(int len)
{
	assert(m_fd!=-1);
#ifdef WIN32
	return ::SetEndOfFile((HANDLE)::_get_osfhandle(m_fd));
#else
	return (ftruncate(m_fd,len) == 0);
#endif
} 

bool CSysFile::IsOpened()
{
	return (m_fd!=-1);
}